package com.moli.iov.admin.web.controller;

import com.moli.iov.admin.constants.Constants;
import com.moli.iov.admin.model.vo.req.*;
import com.moli.iov.admin.model.vo.res.VehicleCommandVo;
import com.moli.iov.admin.model.vo.res.VehicleDetailVo;
import com.moli.iov.admin.service.VehicleBaseService;
import com.moli.iov.base.enums.QueryParamEnum;
import com.moli.iov.base.model.dto.req.*;
import com.moli.iov.base.model.dto.res.VehicleBaseQueryListResDto;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.ExcelUtil;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 车载终端
 *
 * @author whl
 */
@Slf4j
@RequestMapping("/monitor")
@RestController
public class VehicleBaseController extends BaseController {

    @Autowired
    private VehicleBaseService vehicleBaseService;

    @GetMapping("/vehicleDetails/data")
    @ResponseBody
    public RestResponse<VehicleDetailVo> getVehicleDetailByVin(String vin) throws Exception {
        return vehicleBaseService.getVehicleDetail(vin);
    }

    /**
     * 车辆管理图形
     */
    @PostMapping("/vehicleManagement/graphics/list")
    public RestResponse listGraphicsVehicle(
            @Validated @RequestBody VehicleGraphicsQueryListReqVo reqVo) {
        assembleUserInfo(reqVo);
        VehicleGraphicsQueryListReqDto dto = new VehicleGraphicsQueryListReqDto();
        CommonUtils.copyProperties(reqVo, dto);
        if (reqVo.getIsAttention().intValue() == 1) {
            RestResponse res = vehicleBaseService.queryAttentionVehicleGraphics(dto);
            if (res == null) {
                res = RestResponse.success();
            }
            return res;
        } else {
            RestResponse res = vehicleBaseService.listVehicleGraphicsQueryListRes(dto);
            if (res == null) {
                res = RestResponse.success();
            }
            return res;
        }
    }

    /**
     * 车辆管理列表
     */
    @PostMapping("/vehicleManagement/list")
    public RestResponse listVehicle(
            @Validated @RequestBody QueryVehicleBaseListReqVo vo) {
        assembleUserInfo(vo);
        return list(vo);
    }

    private RestResponse list(QueryVehicleBaseListReqVo vo){
        QueryVehicleBaseListReqDto reqDto = new QueryVehicleBaseListReqDto();
        CommonUtils.copyProperties(vo, reqDto);
        if (vo != null && StringUtils.isNotBlank(vo.getVin())) {
            reqDto.setQueryParam(QueryParamEnum.VIN.getCode());
            reqDto.setQueryValue(vo.getVin());
        }
        if (vo != null && StringUtils.isNotBlank(vo.getLicense())) {
            reqDto.setQueryParam(QueryParamEnum.LICENSE.getCode());
            reqDto.setQueryValue(vo.getLicense());
        }
        RestResponse res = null;
        if (vo.getIsAttention().intValue() == 1) {
            log.info("关注列表返回值：请求开始");
            res = vehicleBaseService.queryAttentionVehicleList(reqDto);
            log.info("关注列表返回值：{}",res.toString());
            return res;
        } else {
            res = vehicleBaseService.listVehicleQueryListRes(reqDto);
            return res;
        }
    }



    /**
     * 添加车辆
     */
    @PostMapping("/vehicleManagement/vehicle/save")
    public RestResponse saveVehicleBase(
            @Validated({VehicleBaseVo.Save.class}) @RequestBody VehicleBaseVo vo) {
        assembleUserInfo(vo);
        VehicleBaseReqDto dto = new VehicleBaseReqDto();
        CommonUtils.copyProperties(vo, dto);
        return vehicleBaseService.saveVehicleBase(dto);
    }

    /**
     * 修改车辆
     */
    @PostMapping("/vehicleManagement/vehicle/update")
    public RestResponse updateVehicleBase(
            @Validated({VehicleBaseVo.Update.class}) @RequestBody VehicleBaseVo vo) {
        assembleUserInfo(vo);
        VehicleBaseReqDto dto = new VehicleBaseReqDto();
        CommonUtils.copyProperties(vo, dto);
        return vehicleBaseService.updateVehicleBase(dto);
    }

    /**
     * Batch add vehicle attention.
     *
     * @param vo Vehicle attention value object.
     * @return Restful for response result.
     */
    @PostMapping("/vehicleManagement/vehicleAttention/save")
    public RestResponse batchVehicleAttention(@Validated(VehicleBatchAttentionVo.Save.class) @RequestBody VehicleBatchAttentionVo vo) {
        assembleUserInfo(vo);
        VehicleAttentionReqDto dto = new VehicleAttentionReqDto();
        CommonUtils.copyProperties(vo, dto);
        log.info("添加关注组，入参：{}", dto);
        return vehicleBaseService.saveVehicleAttention(dto);
    }

    /**
     * Batch update vehicle attention.
     *
     * @param vo Vehicle attention value object.
     * @return Restful for response result.
     */
    @PostMapping("/vehicleManagement/vehicleAttention/update")
    public RestResponse updateVehicleAttention(@Validated(VehicleBatchAttentionVo.Update.class) @RequestBody VehicleBatchAttentionVo vo) {
        assembleUserInfo(vo);
        UpdateVehicleAttentionReqDto dto = new UpdateVehicleAttentionReqDto();
        dto.setVin(vo.getVinList().get(0));
        CommonUtils.copyProperties(vo, dto);
        return vehicleBaseService.updateVehicleAttention(dto);
    }

    /**
     * Batch remove vehicle attention.
     *
     * @param vo Vehicle attention value object.
     * @return Restful for response result.
     */
    @PostMapping("/vehicleManagement/vehicleAttention/delete")
    public RestResponse deleteVehicleAttention(@Validated(VehicleBatchAttentionVo.Delete.class) @RequestBody VehicleBatchAttentionVo vo) {
        assembleUserInfo(vo);
        VehicleAttentionReqDto dto = new VehicleAttentionReqDto();
        CommonUtils.copyProperties(vo, dto);
        return vehicleBaseService.deleteVehicleAttention(dto);
    }

    @PostMapping("/vehicleManagement/vehicleAttention/delete/batch")
    public RestResponse batchDeleteVehicleAttention(@RequestBody VehicleBatchDeleteAttentionVo vehicleBatchDeleteAttentionVo) {

        if (vehicleBatchDeleteAttentionVo != null && vehicleBatchDeleteAttentionVo.getList()!=null) {

            Map<Long, Set<String>> map = new HashMap<>();

            for (VehicleBatchDelAttentionVo vehicleBatchDelAttentionVo : vehicleBatchDeleteAttentionVo.getList()) {
                if (vehicleBatchDelAttentionVo != null) {
                    Set<String> set = map.get(vehicleBatchDelAttentionVo.getGroupId());
                    if (set == null) {
                        set = new HashSet<>();
                    }
                    set.add(vehicleBatchDelAttentionVo.getVin());
                    map.put(vehicleBatchDelAttentionVo.getGroupId(), set);
                }
            }

            try {
                for (Map.Entry<Long, Set<String>> longSetEntry : map.entrySet()) {
                    VehicleBatchAttentionVo vo = new VehicleBatchAttentionVo();
                    assembleUserInfo(vo);
                    vo.setGroupId(longSetEntry.getKey());
                    vo.setVinList(new ArrayList<>(longSetEntry.getValue()));
                    vo.setOnlineReminder(0);
                    VehicleAttentionReqDto dto = new VehicleAttentionReqDto();
                    CommonUtils.copyProperties(vo, dto);
                    vehicleBaseService.deleteVehicleAttention(dto);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return RestResponse.failure("操作错误");
            }
        }

        return RestResponse.success();
    }

//  /**
//   * 添加关注车辆
//   */
//  @Deprecated
//  @PostMapping("/vehicleManagement/vehicleAttention/save")
//  public RestResponse saveVehicleAttention(@Validated(VehicleAttentionVo.Save.class) @RequestBody VehicleAttentionVo vo) {
//    assembleUserInfo(vo);
//    VehicleAttentionReqDto dto = new VehicleAttentionReqDto();
//    CommonUtils.copyProperties(vo, dto);
//    return vehicleBaseService.saveVehicleAttention(dto);
//  }

//  /**
//   * 取消关注车辆
//   */
//  @PostMapping("/vehicleManagement/vehicleAttention/delete")
//  public RestResponse deleteVehicleAttention (@Validated(VehicleAttentionVo.Delete.class) @RequestBody VehicleAttentionVo vo) {
//    assembleUserInfo(vo);
//    VehicleAttentionReqDto dto = new VehicleAttentionReqDto();
//    CommonUtils.copyProperties(vo, dto);
//    return vehicleBaseService.deleteVehicleAttention(dto);
//  }

    /**
     * 车辆管理列表
     */
    @PostMapping("/vehicleManagement/export")
    public RestResponse listVehicleExport(
            @Validated @RequestBody QueryVehicleBaseListReqVo vo, HttpServletResponse response,
            HttpServletRequest request) {
        assembleUserInfo(vo);
        vo.setPageNum((long) 1);
        vo.setPageSize(Constants.EXPORT_PAGE_SIZE);
        RestResponse restResponse = list(vo);

        List<VehicleBaseQueryListResDto> resDtos = new ArrayList<>();
        if (restResponse != null && restResponse.isFlag() && restResponse.getData() != null) {
            Map<String, Object> resMap = (Map<String, Object>) restResponse.getData();
            resDtos = (List<VehicleBaseQueryListResDto>) resMap
                    .get("records");
        }

        String[] propNames = {"vin", "license", "onLineStatusStr",
                "keyStatus", "powerStall", "powerState", "instrumentMileage", "cumulativeMileage"
                , "extendGpsOde", "companyName"};
        String[] headStr = {"车架号", "车牌号", "在线状态",  "钥匙状态", "电源档位",
                "动力状态", "仪表里程", "实际里程", "GPS里程", "所属企业"};
        String title = "车辆管理";
        try {
            ExcelUtil.exportDataExcel(request, response, resDtos, propNames, headStr, title);
            return RestResponse.success();
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure("导出异常");
        }
    }

    /* *
     * 车辆详情
     *
     * @param vin
     * @return
     * @throws Exception*/
    @PostMapping("/vehicleManagement/details")
    public RestResponse<VehicleDetailVo> getVehicleDetailByVin(
            @Validated({VehicleBaseVo.Details.class}) @RequestBody VehicleBaseVo vo) {
        try {
            return vehicleBaseService.getVehicleDetail(vo.getVin());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure("查看失败");
        }
    }

    /* *
     * 车辆空车命令
     *  VehicleStatusDto
     * @param vin
     * @return
     * @throws Exception*/
    @PostMapping("/vehicleManagement/commandList")
    public RestResponse<VehicleCommandVo> getCommandList(
            @Validated({VehicleBaseVo.Details.class}) @RequestBody VehicleBaseVo vo) {
        try {
            return vehicleBaseService.getVehicleCommandList(vo.getVin());
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure("查看失败");
        }
    }

    @GetMapping("/vehicleManagement/attention/group")
    public RestResponse<List<Map<String, Object>>> queryAllVehicleCtlCommands() {
        BaseVo baseVo = getBaseVo();
        return vehicleBaseService.queryAttentionGroup(baseVo.getSysUserId());
    }

    /**
     * 添加关注组
     */
    @PostMapping("/vehicleManagement/attention/group/save")
    public RestResponse saveVehicleFollowGroup(@Validated(VehicleFollowGroupReqDto.Save.class) @RequestBody VehicleFollowGroupVo vo) {
        assembleUserInfo(vo);
        VehicleFollowGroupReqDto dto = new VehicleFollowGroupReqDto();
        dto.setUserId(vo.getSysUserId());
        dto.setCompanyId(vo.getSysCompanyId());
        dto.setCompanyName(vo.getSysCompanyName());
        dto.setGmtCreate(new java.util.Date());
        dto.setGmtModified(new java.util.Date());
        CommonUtils.copyProperties(vo, dto);
        return vehicleBaseService.saveVehicleFollowGroup(dto);
    }

    /**
     * 取消关注组
     */
    @PostMapping("/vehicleManagement/attention/group/delete")
    public RestResponse deleteVehicleFollowGroup(@RequestBody VehicleFollowGroupDeleteDto vo) {
        if(vo==null ||vo.getId()==null){
            return RestResponse.failure("grouId不能为空");
        }
        assembleUserInfo(vo);
        VehicleFollowGroupReqDto dto = new VehicleFollowGroupReqDto();
        dto.setUserId(vo.getSysUserId());
        dto.setCompanyId(vo.getSysCompanyId());
        dto.setCompanyName(vo.getSysCompanyName());
        dto.setGmtCreate(new java.util.Date());
        dto.setGmtModified(new java.util.Date());
        CommonUtils.copyProperties(vo, dto);
        return vehicleBaseService.deleteVehicleFollowGroup(dto);
    }


}